package com.woniuxy.store.app.apiImpl;

import cn.hutool.core.io.FileUtil;
import com.woniuxy.cloud.mall95.log.Log;
import com.woniuxy.food.client.foodpicclient.FoodPicManageClient;
import com.woniuxy.food.client.foodpicclient.FoodPicQueryClient;
import com.woniuxy.store.app.util.CheckImage;
import com.woniuxy.store.app.util.StoreIdUtil;
import com.woniuxy.store.client.FoodPicClient;
import com.woniuxy.store.service.util.OSSUtil;
import exception.MallException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import result.CommonResultCodeEnum;
import result.Result;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/store/food")
public class FoodPicClientImpl implements FoodPicClient {
    @Autowired
    private FoodPicManageClient foodPicManageClient;
    @Autowired
    private FoodPicQueryClient foodPicQueryClient;
    @Autowired
    private OSSUtil ossUtil;

    @Override
    @Log("商家添加图片库")
    public Result insertFoodPic(MultipartFile file) {
        InputStream inputStream = null;
        String fileName = null;
        try {
            inputStream = file.getInputStream();
            fileName = file.getOriginalFilename();
            //限制文件上传类型
            if (!CheckImage.isImage(file)) {
                throw new MallException("该文件不是一张图片", CommonResultCodeEnum.INVALID_PARAM);
            }
        } catch (IOException e) {
            throw new MallException("图片解析错误",CommonResultCodeEnum.INVALID_PARAM);
        }
        //取出后缀名
        String suffix = FileUtil.getSuffix(fileName);
        String s = UUID.randomUUID().toString().replaceAll("-","");
        String url = ossUtil.uploadFile(inputStream, s + "." + suffix, "zjr-bucket");
        return foodPicManageClient.insertFoodPic(StoreIdUtil.getFromToken(),url);
    }

    @Override
    @Log("商家从图片库删除图片")
    public Result deleteFoodPic(Integer foodPicId) {
        return foodPicManageClient.deleteFoodPic(StoreIdUtil.getFromToken(),foodPicId);
    }

    @Override
    @Log("商家查询图片库全部图片")
    public Result searchFoodPic() {
        return foodPicQueryClient.searchFoodPic(StoreIdUtil.getFromToken());
    }
}
